﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using WAU.Common;
using WAU.Models.AppUserModels;
using WAU.Models.WhereAreYouModels;
using WAU.Services;

namespace WAU.Controllers
{
    /// <summary>
    /// WAU 控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [Authorize]
    [ApiController]
    public class WhereAreYouController : EssentialController
    {
        private const string WAU_CACHE_KEY = "WAU-Cache";

        private static object lockObj = new object();

        private MemoryCacheForComponent Cache = new MemoryCacheForComponent(WAU_CACHE_KEY);

        private readonly AppUserService _appUserService;

        /// <summary>
        /// ctor
        /// </summary>
        /// <param name="appUserService"></param>
        public WhereAreYouController(AppUserService appUserService)
        {
            this._appUserService = appUserService;
        }

        /// <summary>
        /// 设置 WAU 位置
        /// </summary>
        /// <param name="reqM"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SetPosition(SetPositionReqM reqM)
        {
            string currentUserId = HttpContext.User.Identity.Name;

            PositionItem positionItem = new PositionItem
            {
                WAUPosition = new WAUPosition
                {
                    Latitude = reqM.WAUPosition.Latitude,
                    Longitude = reqM.WAUPosition.Longitude
                },
                UserId = currentUserId,
                SetTime = DateTime.Now
            };

            lock (lockObj)
            {
                bool getCacheResult = Cache.TryGetCacheValue("default", out List<PositionItem> positionList);
                if (!getCacheResult)
                {
                    positionList = new List<PositionItem> { positionItem };
                }

                var existQuery = positionList.Where(a => a.UserId == currentUserId);
                if (existQuery.Any())
                {
                    PositionItem existItem = existQuery.FirstOrDefault();
                    positionList.Remove(existItem);
                }

                positionList.Add(positionItem);

                Cache.SetCache("default", positionList, new MemoryCacheEntryOptions());
            }

            return Ok(new Result { Success = true });
        }

        /// <summary>
        /// 获取 WAU 位置
        /// </summary>
        /// <param name="reqM"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult> GetPosition(GetPositionReqM reqM)
        {
            string currentUserId = HttpContext.User.Identity.Name;
            if(currentUserId == reqM.TargetUserId)
            {
                return BusinesssError(new Result
                {
                    Success = false,
                    Msg = "请不要获取自己的位置信息哦！"
                });
            }

            AppUser appUser = (await _appUserService.FetchUsers(new List<string> { reqM.TargetUserId })).FirstOrDefault();
            if (appUser == null)
            {
                return BusinesssError(new Result
                {
                    Success = false,
                    Msg = "目标用户不存在！"
                });
            }

            bool getCacheResult = Cache.TryGetCacheValue("default", out List<PositionItem> positionList);
            if (!getCacheResult)
            {
                return BusinesssError(new Result
                {
                    Success = false,
                    Msg = "未获取到任何位置信息！"
                });
            }

            var query = positionList.Where(a => a.UserId == reqM.TargetUserId);
            if (query.Any())
            {
                PositionItem existItem = query.FirstOrDefault();
                return Ok(new Result
                {
                    Success = true,
                    Msg = "获取成功",
                    Data = existItem
                });
            }
            else
            {
                return BusinesssError(new Result
                {
                    Success = false,
                    Msg = $"未获取到 { appUser.RealName } 的位置信息！"
                });
            }
        }
    }
}
